package o2s.contentprovider;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import my.example.samplegridview.modal.category;
import my.example.samplegridview.modal.categorydescription;
import my.example.samplegridview.modal.product;
import my.example.samplegridview.modal.product_discount;
import my.example.samplegridview.modal.product_option;
import my.example.samplegridview.modal.product_option_description;
import my.example.samplegridview.modal.product_option_value;
import my.example.samplegridview.modal.product_option_value_description;
import my.example.samplegridview.modal.product_to_category;
import my.example.samplegridview.modal.productdescription;
import my.example.samplegridview.modal.review;
import o2s.utils.StringHelper;

import org.apache.http.util.ByteArrayBuffer;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;

public class datacontentprovider extends  ContentProvider{
	public static final String AUTHORITY = "o2s.contentprovider.datacontentprovider";
	public static SQLiteDatabase sqlDB;
	public static DatabaseHelper dbHelper;
	private static final String DATABASE_NAME    = "O2S.db";
    private static final int    DATABASE_VERSION = 3;
    private static String TABLE_NAME       = "";
    public static final String review_id = "review_id";
    public static final String product_id = "product_id";
    public static final String customer_id = "customer_id";
    public static final String author = "author";
    public static final String text = "text";
    public static final String rating = "rating";
    public static final String status = "status";
    public static final String date_added = "date_added";
    public static final String date_modified = "date_modified";
	
	public static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
        	Log.d("o2s", "Start create Db");
        	syncProcessStart(db);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }
	
	public static boolean dropTable(){
		try{
			
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + review.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + product.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + productdescription.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + category.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + categorydescription.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + product_option.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + product_option_description.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + product_option_value.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + product_option_value_description.Table);
			dbHelper.getWritableDatabase().execSQL("DROP TABLE IF EXISTS " + product_discount.Table);
			
			return true;
		}
		catch(Exception e){
			//Log.d("o2s", e.getMessage());
			String tmp = e.getMessage();
			String tmp2 = tmp;
			return false;
		}
	}
	
	@Override
	public int delete(Uri arg0, String arg1, String[] arg2) {
		getCorrespondingTable(arg0);
		sqlDB = dbHelper.getWritableDatabase();
		return sqlDB.delete(TABLE_NAME, arg1, arg2);
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		getCorrespondingTable(uri);
		// get database to insert records
        sqlDB = dbHelper.getWritableDatabase();
        // insert record in user table and get the row number of recently inserted record
        long rowId = sqlDB.insert(TABLE_NAME, "", values);
        if (rowId > 0) {
            Uri rowUri = ContentUris.appendId(uri.buildUpon(), rowId).build();
            getContext().getContentResolver().notifyChange(rowUri, null);
            return rowUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		dbHelper = new DatabaseHelper(getContext());
        return (dbHelper == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		getCorrespondingTable(uri);
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		getCorrespondingTable(uri);
		sqlDB = dbHelper.getWritableDatabase();
		return sqlDB.update(TABLE_NAME, values, selection, selectionArgs);
	}
	
	public void getCorrespondingTable(Uri uri){
		
		if(uri == review.CONTENT_URI){
			TABLE_NAME = review.Table;
		}
		else if(uri == product.CONTENT_URI){
			TABLE_NAME = product.Table;
		}
		else if(uri == productdescription.CONTENT_URI){
			TABLE_NAME = productdescription.Table;
		}
		else if(uri == category.CONTENT_URI){
			TABLE_NAME = category.Table;
		}
		else if(uri == categorydescription.CONTENT_URI){
			TABLE_NAME = categorydescription.Table;
		}
		else if(uri == product_to_category.CONTENT_URI){
			TABLE_NAME = product_to_category.Table;
		}
		else if(uri == review.CONTENT_URI){
			TABLE_NAME = review.Table;
		}
		else if(uri == product_option.CONTENT_URI){
			TABLE_NAME = product_option.Table;
		}
		else if(uri == product_option_description.CONTENT_URI){
			TABLE_NAME = product_option_description.Table;
		}
		else if(uri == product_option_value.CONTENT_URI){
			TABLE_NAME = product_option_value.Table;
		}
		else if(uri == product_option_value_description.CONTENT_URI){
			TABLE_NAME = product_option_value_description.Table;
		}
		else if(uri == product_discount.CONTENT_URI){
			TABLE_NAME = product_discount.Table;
		}
	}
	
	public static void syncProcessStart(SQLiteDatabase db){
		try{
        	db.execSQL(review.SQLCREATE);
        	db.execSQL(product.SQLCREATE);
        	db.execSQL(productdescription.SQLCREATE);
        	db.execSQL(category.SQLCREATE);
        	db.execSQL(categorydescription.SQLCREATE);
        	db.execSQL(product_to_category.SQLCREATE);
        	db.execSQL(product_option.SQLCREATE);
        	db.execSQL(product_option_description.SQLCREATE);
        	db.execSQL(product_option_value.SQLCREATE);
        	db.execSQL(product_option_value_description.SQLCREATE);
        	db.execSQL(product_discount.SQLCREATE);
        	
        	syncProcess("opencart_product","o2s_product",db);
        	syncProcess("opencart_product_description","o2s_product_description",db);
        	syncProcess("opencart_category","o2s_category",db);
        	syncProcess("opencart_category_description","o2s_category_description",db);
        	syncProcess("opencart_product_to_category","o2s_product_to_category",db);
        	syncProcess("opencart_product_option","o2s_product_option",db);
        	syncProcess("opencart_product_option_description","o2s_product_option_description",db);
        	syncProcess("opencart_product_option_value","o2s_product_option_value",db);
        	syncProcess("opencart_product_option_value_description","o2s_product_option_value_description",db);
        	syncProcess("opencart_product_discount","o2s_product_discount",db);
        	
        	//db.execSQL("VACUUM ;");
        }
        catch(Exception e){
        	String t1 = e.getMessage();
        	String t2 = "";
        }
	}

	public static void syncProcess(String tableName , String replaceTableName , SQLiteDatabase db){
		String urlPath = "http://www1.churrosroyale.com/opencart/main/index.php?route=export/qe&u=o2s&p=o2salive&tableInfo="+tableName;
		URL url = null;
		String myString = "";
		String tey = "";
		try{
			url = new URL(urlPath);
			URLConnection urlConn = url.openConnection();
            
            InputStream is = urlConn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
           
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while((current = bis.read()) != -1){
            baf.append((byte)current); 
            }
            myString = new String(baf.toByteArray());
            myString = StringHelper.unescape(myString);
            String[] splittedQuery = myString.split(";\n");
            String tmp = "";
        	//android.text.TextUtils.htmlEncode();
            for(int i=0;i<splittedQuery.length;i++){
            	tmp = splittedQuery[i].replaceAll(tableName, replaceTableName);
            	if(tmp.trim().length() > 0)
            		db.execSQL(tmp+";\n");
            }
		}
		catch(Exception e){
			tey = e.getMessage();
			String yerString = tey;
		}
	}
}
